package com.blt.govdata.controller;

import com.baomidou.mybatisplus.entity.Column;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.blt.govdata.controller.base.BaseController;
import com.blt.govdata.core.constants.Constants;
import com.blt.govdata.model.TProject;
import com.blt.govdata.model.TProjectEvolve;
import com.blt.govdata.model.TProjectSupervisor;
import com.blt.govdata.service.ITProjectEvolveService;
import com.blt.govdata.service.ITProjectService;
import com.blt.govdata.service.ITProjectSupervisorService;
import com.blt.govdata.utils.CommonUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.ObjectArrays;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 * @author AustinGJ123
 * @since 2018-03-26
 */
@RestController
@RequestMapping("/tProjectSupervisor")
//todo 将所有的XXX修改为真实值
public class TProjectSupervisorController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ITProjectSupervisorService service;

    @Autowired
    private ITProjectService projectService;

    @Autowired
    private ITProjectEvolveService evolveService;

    /**
     * 分页查询工作落实(t_project_supervisor/t_project_evolve)
     */

    @RequestMapping(value = "/selectWorkPracticablePage")
    public Map<String, Object> selectWorkPracticablePage(@RequestParam Map<String, Object> params, Page page) {


        /**
         * 查询已有工作落实的项目id
         * */
        Page<Map<String,Integer>> pIdMaps = this.service.selectMapsPage(page,BeanUtils.instantiate(EntityWrapper.class).setSqlSelect("p_id")
                .where("is_delete = {0}",Constants.UN_DELETED)
                .and("examine_state = {0}",Constants.AUDITED_PASS)
                .groupBy("p_id"));

        List<Map<String,Integer>> listMap = pIdMaps.getRecords();

        if(CollectionUtils.isEmpty(listMap)) return ImmutableMap.of("status", "true", "data", pIdMaps);

        List<Integer> pIds = listMap.stream().map(e->e.get("p_id")).collect(Collectors.toList());

        List<Map<String,Object>> list = this.projectService.selectMaps(BeanUtils.instantiate(EntityWrapper.class)
                .setSqlSelect(BeanUtils.instantiate(Column.class).column("id"),BeanUtils.instantiate(Column.class).column("name"))
                .in("id",pIds)
                .where("examine_state = {0}",Constants.AUDITED_PASS)
                .like("name",(String)params.get("keyword")));

        Iterator it = list.iterator();
        while(it.hasNext()){
            Map<String,Object> map = (Map<String,Object>)it.next();
            Integer id = (Integer)map.get("id");
            params.put("id",id);
            map.put("workPracticable",this.service.selectProjectSupervisor(params));
        }
        page.setRecords(list);
        logger.info("分页查询项目完成状态");
        return ImmutableMap.of("status", "true", "data", page);
    }

    /**
     * 分页查询工作进展
     */
    @RequestMapping(value = "/page")
    public Map<String, Object> selectPage(@RequestParam Map<String, Object> params, Page<TProject> page) {

        EntityWrapper ew = new EntityWrapper();
        ew.setSqlSelect("id","name");
        ew.where("examine_state = {0}",Constants.AUDITED_PASS);
        if(!StringUtils.containsAny(this.username,"admin","super")) ew.and("principal = {0}",this.userid);
        ew.like("name",(String)params.get("keyword"));

        Page<Map<String,Object>> listPage = this.projectService.selectMapsPage(page,ew);

        List<Map<String,Object>> list = listPage.getRecords();
        if(!CollectionUtils.isEmpty(list)){
            Iterator it = list.iterator();
            while(it.hasNext()){
                Map<String,Object> map = (Map<String,Object>)it.next();
                Integer id = (Integer)map.get("id");
                params.put("id",id);
                map.put("supervisor",this.service.selectProjectSupervisor(params));
            }
        }
        logger.info("分页查询项目完成状态");
        return ImmutableMap.of("status", "true", "data", listPage);
    }

    /**
     * 分页查询任务管理(有条件)
     */
    @RequestMapping(value = "/task/page")
    public Map<String, Object> selectTaskPage(@RequestParam Map<String, Object> params, Page page) {
        /**
         * 查询已有工作任务的项目id
         * */
        Page<Map<String,Integer>> pIdMaps = this.service.selectMapsPage(page,BeanUtils.instantiate(EntityWrapper.class).setSqlSelect("p_id")
                .where("is_delete = {0}",Constants.UN_DELETED)
                .and("examine_state = {0}",Constants.AUDITED_PASS)
                .groupBy("p_id"));

        List<Map<String,Integer>> listMap = pIdMaps.getRecords();

        if(CollectionUtils.isEmpty(listMap)) return ImmutableMap.of("status", "true", "data", pIdMaps);

        List<Integer> pIds = listMap.stream().map(e->e.get("p_id")).collect(Collectors.toList());

        List<Map<String,Object>> list = this.projectService.selectMaps(BeanUtils.instantiate(EntityWrapper.class)
                .setSqlSelect(BeanUtils.instantiate(Column.class).column("id"),BeanUtils.instantiate(Column.class).column("name"))
                .in("id",pIds)
                .where("examine_state = {0}",Constants.AUDITED_PASS)
                .like("name",(String)params.get("keyword")));
        Iterator it = list.iterator();
        while(it.hasNext()){
            Map<String,Object> map = (Map<String,Object>)it.next();
            Integer id = (Integer)map.get("id");
            params.put("id",id);
            map.put("supervisor",this.service.selectProjectSupervisor(params));
        }
        logger.info("分页查询项目任务管理");
        page.setRecords(list);
        return ImmutableMap.of("status", "true", "data", page);
    }


    /**
     * 新增任务管理（需要改为多选）
     */
    @RequestMapping(value = "/addProjectSupervisor")
    public Map<String, Object> addProjectSupervisor(TProjectSupervisor supervisor) {
        boolean result = this.service.insert(supervisor);
        return ImmutableMap.of("status", "true", "data", result);
    }

    /**
     * 编辑工作进展
     */
    @RequestMapping(value = "/editProjectSupervisor",params = {"supervisorId"})
    public Map<String, Object> editProjectSupervisor(TProjectSupervisor tProjectSupervisor, TProjectEvolve tProjectEvolve,Integer supervisorId) {
        tProjectSupervisor.setId(supervisorId);
        boolean a = this.service.updateById(tProjectSupervisor);
        boolean b = false;
        TProjectEvolve one = this.evolveService.selectOne(BeanUtils.instantiate(EntityWrapper.class).where("s_id = {0}",supervisorId));
        if(null == one) {
            tProjectEvolve.setsId(supervisorId);
            b = this.evolveService.insert(tProjectEvolve);
        }else{
            b = this.evolveService.update(tProjectEvolve,BeanUtils.instantiate(EntityWrapper.class).where("s_id = {0}",supervisorId));
        }
        return ImmutableMap.of("status", "true", "data", a&b);
    }

    /**
     * 删除任务管理
     */
    @RequestMapping(value = "/deleteProjectSupervisor", params = {"id"})
    public Map<String, Object> deleteProjectSupervisor(Integer id) {
        TProjectSupervisor tProjectSupervisor = BeanUtils.instantiate(TProjectSupervisor.class);
        tProjectSupervisor.setId(id);
        tProjectSupervisor.setIsDelete(Constants.IS_DELETED);
        boolean result = this.service.updateById(tProjectSupervisor);
        return ImmutableMap.of("status", "true", "data", result);
    }


    /**
     * 根据ID查询工作进展
     */
    @RequestMapping(value = "/selectProjectSupervisorById", params = {"id"})
    public Map<String, Object> selectProjectSupervisorById(Integer id) {
        Map<String,Object> params = Maps.newHashMap();
        params.put("supervisorId",id);
        return ImmutableMap.of("status", "true", "data", this.service.selectProjectSupervisor(params));
    }
}
